﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Hardanger.Model;
using System.IO;

namespace Hardanger.Features
{
    public class TCPWebResponse
    {
		private string _httpVersion = null;
		public string HttpVersion
		{
			get
			{
				if (_httpVersion == null)
				{
					ParseResponse();
				}
				return _httpVersion;
			}
		}
		private string _statusMessage = null;
		public string StatusMessage
		{
			get
			{
				if (_statusMessage == null)
				{
					ParseResponse();
				}
				return _statusMessage;
			}
		}
		private string _statusCode = null;
        public string StatusCode
        {
            get
            {
				if (_statusCode == null)
				{
					ParseResponse();
				}
				return _statusCode;
            }
        }

		private string _body = null;
		public string Body
		{
			get
			{
				if (_body == null)
				{
					ParseResponse();
				}
				return _body;
			}
		}
		private Dictionary<string,string> _headers = null;
		public Dictionary<string, string> Headers
		{
			get
			{
				if (_headers == null)
				{
					ParseResponse();
				}
				return _headers;
			}
		}
		
		private void ParseResponse()
		{
			_headers = new Dictionary<string, string>();
			using (StringReader sr = new StringReader(Raw))
			{
				string firstLine = sr.ReadLine();
				string[] firstLineParts = firstLine.Split(new char[] { ' ' }, 3);
				_httpVersion = firstLineParts[0];
				_statusCode = firstLineParts[1];
				_statusMessage = firstLineParts[2];

				while (sr.Peek() >= 0)
				{
					string line = sr.ReadLine();
					if (string.IsNullOrEmpty(line))
					{
						//we are done reading headers
						_body = sr.ReadToEnd();
						break;
					}
					string[] parts = line.Split(new char[] { ':' }, 2);
					_headers.Add(parts[0], parts[1].TrimStart(new char[] { ' ' }));
				}
			}
		}
        public string Raw { get; set; }
		
    }
}
